package com.rent.message.ws;

import com.rent.common.constant.CommonConstant;
import com.rent.message.constant.MessageConstant;
import com.rent.message.pojo.dto.SystemMessageDto;
import com.rent.message.pojo.entity.ChatMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service
@Slf4j
public class MessagePushService {
    
    @Autowired
    private SimpMessagingTemplate messagingTemplate;
    
    @Autowired
    private MessageSessionService sessionService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    
    /**
     * 发送消息给用户（在任何地方调用）
     */
    public void sendToUser(String userId,  Map<String, Object> message) {
        log.info("=== 开始推送消息给用户: {} ===", userId);
        log.info("消息内容: {}", message);

        Set<Object> uuids = sessionService.getUserUuids(userId);
        log.info("用户 {} 的会话数量: {}", userId, uuids.size());

        if (!uuids.isEmpty()) {
            boolean sent = false;
            for (Object uuidsObj : uuids) {
                String uuid = uuidsObj.toString();
                log.info("用户 {} 的uuid{}", userId,uuid);
                try {
                    log.info("尝试向会话 {} 推送消息", uuid);

                    // 关键：使用正确的目的地格式
                    messagingTemplate.convertAndSendToUser(
                            uuid,
                            "/queue/messages",
                            message
                    );

                    log.info("✅ 消息成功推送给用户: {}, uuid会话: {}", userId, uuid);
                    sent = true;

                } catch (Exception e) {
                    log.error("❌ 推送消息失败，移除无效会话: {}", uuid, e);
//                    sessionService.removeSession(sessionId);
                }
            }

            if (!sent) {
                log.warn("用户 {} 的所有会话推送都失败了", userId);
            }
        } else {
            log.info("用户 {} 不在线，仅保存消息到数据库", userId);
        }

        //拿到当前用户对话的对象的id
        Object fromUserObj = redisTemplate.opsForValue().get(MessageConstant.CHAT_USER_ID + userId);
        Long fromUser = null;
        if (fromUserObj instanceof Integer) {
            fromUser = ((Integer) fromUserObj).longValue();
        } else if (fromUserObj instanceof Long) {
            fromUser = (Long) fromUserObj;
        }

        ChatMessage chatMessage = new ChatMessage();
        if(fromUser != null && fromUser.equals(message.get("fromUserId"))){
            chatMessage.setIsRead(1);
        }else {
            chatMessage.setIsRead(0);
        }

        chatMessage.setId(Long.parseLong(message.get("id").toString()));
        chatMessage.setPostUserId(Long.parseLong(message.get("fromUserId").toString()));
        chatMessage.setGetUserId(Long.parseLong(userId));
        chatMessage.setContent(message.get("content").toString());
        chatMessage.setPicture(message.get("picture").toString());

        chatMessage.setCreated(new Date());

        // 尝试发送给RabbitMQ
        rabbitTemplate.convertAndSend(CommonConstant.EXCHANGE_NAME, CommonConstant.ROUTING_KEY_CHAT_MESSAGE, chatMessage);


    }

    public void sendNoticeToUser(String userId,  Map<String, Object> message) {
        log.info("=== 开始推送通知消息给用户: {} ===", userId);
        log.info("消息内容: {}", message);

        Set<Object> uuids = sessionService.getUserUuids(userId);
        log.info("用户 {} 的会话数量: {}", userId, uuids.size());

        if (!uuids.isEmpty()) {
            boolean sent = false;
            for (Object uuidsObj : uuids) {
                String uuid = uuidsObj.toString();
                log.info("用户 {} 的uuid{}", userId,uuid);
                try {
                    log.info("尝试向会话 {} 推送消息", uuid);

                    // 关键：使用正确的目的地格式
                    messagingTemplate.convertAndSendToUser(
                            uuid,
                            "/queue/messages",
                            message
                    );

                    log.info("✅ 消息成功推送给用户: {}, 会话: {}", userId, uuid);
                    sent = true;

                } catch (Exception e) {
                    log.error("❌ 推送消息失败，移除无效会话: {}", uuid, e);
//                    sessionService.removeSession(sessionId);
                }
            }

            if (!sent) {
                log.warn("用户 {} 的所有会话推送都失败了", userId);
            }
        } else {
            log.info("用户 {} 不在线", userId);
        }

    }
    
    /**
     * 发送系统消息
     */
    public void broadMessageAllUsers(SystemMessageDto dto) {
        log.info("=== 广播推送系统消息 ===");
        Map<String, Object> message = new HashMap<>();
        message.put("type", MessageConstant.MESSAGE_TYPE_SYSTEM);
        message.put("from", 0L);
        message.put("content", dto.getContent());
        message.put("timestamp", System.currentTimeMillis());

        Set<String> userKeys = redisTemplate.keys(CommonConstant.USER_KEY+"*");
        if (userKeys != null) {
            for (String userKey : userKeys) {
                Set<Object> sessions = redisTemplate.opsForSet().members(userKey);
                if (sessions != null) {
                    for (Object sessionId : sessions) {
                        String uuid = (String) redisTemplate.opsForValue().get(CommonConstant.USER_SESSION_UUID + sessionId.toString());
                        assert uuid != null;
                        messagingTemplate.convertAndSendToUser(
                                uuid,
                                "/queue/messages",
                                message);
                        // 这里需要 SimpMessagingTemplate，可以通过参数传入
                    }
                }
            }
        }
    }


    /*
    * 推送欢迎消息
     */
    public void sendWelcomeMessage(String userId, String uuid) {
        try {
            Map<String, Object> msg = new HashMap<>();
            msg.put("type", MessageConstant.MESSAGE_TYPE_WELCOME);
            msg.put("content", "消息系统连接成功！");
            msg.put("timestamp", System.currentTimeMillis());
            msg.put("id", "welcome_" + System.currentTimeMillis());

            messagingTemplate.convertAndSendToUser(
                    uuid,
                    "/queue/messages",
                    msg
            );
            log.info("欢迎消息发送成功: userId={}, sessionId={}", userId, uuid);
        } catch (Exception e) {
            log.error("发送欢迎消息失败", e);
        }
    }


}